package net.zdreamer.geracomium.utils.window;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

public class ViewControlor {

	/*
	 * Context context上下文对象 View v 一个合适的View s_width, s_height 为了确定宽高的比，推荐用最简比
	 * flag 上两个参数是否有用
	 */
	public static void setSize(Context context, View v, int s_width,
			int s_height, boolean flag) {
		int border = 0;// 两边的距离和
		LinearLayout.LayoutParams vp_pramas = (LinearLayout.LayoutParams) v
				.getLayoutParams();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			vp_pramas.width = WindowUtil.getWindowSize(context).x - border;
			if (flag) {
				vp_pramas.height = (WindowUtil.getWindowSize(context).x - border)
						* s_height / s_width;
			} else {
				vp_pramas.height = WindowUtil.getWindowSize(context).x - border;
			}
			v.setLayoutParams(vp_pramas);
		} else {
			vp_pramas.width = WindowUtil.getWindow(context)[0] - border;
			if (flag) {
				vp_pramas.height = (WindowUtil.getWindow(context)[0] - border)
						* s_height / s_width;
			} else {
				vp_pramas.height = WindowUtil.getWindow(context)[0] - border;
			}
			v.setLayoutParams(vp_pramas);
		}
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		// 获取ListView对应的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		// listView.getDividerHeight()获取子项间分隔符占用的高度
		// params.height最后得到整个ListView完整显示需要的高度
		listView.setLayoutParams(params);
	}

	public static void hideKeyboard(Activity mActivity) {
		InputMethodManager inputManager =
                (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(mActivity.getWindow().getDecorView().getWindowToken(), 0);
	}
}
